﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CoreApp.Hangfire.Core;
using CoreApp.Utility;
using Hangfire;
using Hangfire.SqlServer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;

namespace CoreApp.Hangfire
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //SqlServer（需要先创建空的数据库）
            services.AddHangfire(x => x.UseStorage(new SqlServerStorage(
                Configuration["HangfireConnectionString"],
                new SqlServerStorageOptions
                {
                    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                    QueuePollInterval = TimeSpan.Zero,
                    UseRecommendedIsolationLevel = true,
                    UsePageLocksOnDequeue = true,
                    DisableGlobalLocks = true
                }
            )));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //配置NLog
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//这是为了防止中文乱码
            loggerFactory.AddNLog();//添加NLog
            env.ConfigureNLog("nlog.config");//读取Nlog配置文件

            //使用hangfire面板
            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] { new MyDashboardAuthorizationFilter() }
            });

            //启动hangfire服务
            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                ServerName = "myhangfire",//服务器名称
                Queues = new[] { "myqueue", "default" },//队列名称，只能为小写
                WorkerCount = Environment.ProcessorCount * 5, //并发任务数，超出并发数将等待之前任务的完成 (推荐并发线程是cpu的5倍)
            });

            LoadTasks();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

        public void LoadTasks()
        {
            RecurringJob.AddOrUpdate("1", () => DoWork1(), Cron.Minutely);//每分钟执行一次
            RecurringJob.AddOrUpdate("2", () => DoWork2(), "0 0/3 * * * ? ");//每3分钟执行一次
        }

        public void DoWork1()
        {
            NLogHelper.Info("定时任务1，执行时间为：" + DateTime.Now);
        }

        public void DoWork2()
        {
            NLogHelper.Info("定时任务2，执行时间为：" + DateTime.Now);
        }
    }
}
